package com.lznAdmin.base.common.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: lznAdmin-pro
 * @description: 构建QueryWrapper类
 * @author: lzn
 * @create: 2021-12-30 16:28
 **/
@Slf4j
@Component
public class QueryWrapperUtil {
    @Autowired
    private CommonUtil commonUtil;

    /**
     * 过滤出@TableField(exist == false)的字段
     *
     * @param aClass class对象
     * @param name   字段名称
     * @return Boolean
     */
    private static Boolean isTableField(Class<?> aClass, String name) {
        // 递归查询父类,找出这个字段
        Field field = null;
        try {
            field = aClass.getDeclaredField(name);
        } catch (NoSuchFieldException e) {
            if (aClass.getSuperclass() == Object.class) {
                return true;
            }
            return isTableField(aClass.getSuperclass(), name);
        }

        // 判断是否@TableField(exist == false)，是则返回false
        TableField tableField = field.getAnnotation(TableField.class);
        if (tableField != null) {
            return !tableField.exist();
        }
        return false;
    }

    public <T> QueryWrapper<T> BuildQueryWrapper(T entity, Map<String, String[]> parameterMap) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<T>();

        Map<String, Object> queryField = this.isQueryField(entity);
        // log.info(queryField.toString());
        for (Map.Entry<String, Object> mapEntry : queryField.entrySet()) {
            queryWrapper.like(mapEntry.getKey(), mapEntry.getValue());
        }
        return queryWrapper;
    }

    /**
     * 过滤需查询的map
     *
     * @param entity 查询实体
     * @return stringObjectMap 用于查询的map
     */
    private <T> Map<String, Object> isQueryField(T entity) {
        Map<String, Object> stringObjectMap = new HashMap<>();
        Map<String, Object> QueryFieldMap = BeanUtil.beanToMap(entity, false, true);
        for (Map.Entry<String, Object> mapEntry : QueryFieldMap.entrySet()) {
            Class<?> aClass = entity.getClass();
            Boolean tableField = isTableField(aClass, mapEntry.getKey());
            if (!tableField && !StrUtil.isEmpty(mapEntry.getValue().toString())) {
                // log.info("stringObjectMap = {}",commonUtil.humpToLine(mapEntry.getKey()));
                stringObjectMap.put(commonUtil.humpToLine(mapEntry.getKey()), mapEntry.getValue());
            }
        }
        return stringObjectMap;
    }
}
